<?php

use Workerman\Worker;
use Workerman\Lib\Timer;

include __DIR__ . '/vendor/autoload.php';
//创建一个变量存放所有房间
$connection_all = [];
$timer_all = [];
//创建一个Worker监听127.0.0.1:16670, 使用websocket协议通讯  
$ws_worker = new Worker("websocket://0.0.0.0:84");
//启动4个进程对外提供服务  
$ws_worker->count = 1;
$ws_worker->onWorkerStart = function(){
    Timer::add(1, 'sendStatus', [], true);
};
$ws_worker->onConnect = function($connection) use($ws_worker, &$connection_all) {
    echo "\n" . $connection->getRemoteIp() . "连接服务器!连接id：{$connection->id} \n";

};

//当接收到客户端发来的数据后显示数据并回发到客户端 
$ws_worker->onMessage = function($connection, $data) use ($ws_worker, &$connection_all, &$timer_all) {
    $baseUrl = "http://localhost/api/";
    // $baseUrl = "http://api.xslfgame.com/";
    $ip = $connection->getRemoteIp();
    if ($ip == '127.0.0.1') {
        $data = str_replace('\\"', '"', str_replace('\r\n', '', $data));
        $data = ltrim($data, '"');
        $data = rtrim($data, '"');
    }
    
    //判断数据是不是@
    if ($data == '@') {
        $connection->send('@');
    }else{
        //显示数据  
        echo "you just received:     $data\n";
    }
    //解析数据
    $dataInfo = json_decode($data, true);

//数据分发
    if ($dataInfo && isset($dataInfo['operation'])) {
        switch ($dataInfo['operation']) {
            case "JoinRoom"://进入房间获取状态 user_id game_id
                if (isset($dataInfo['user_id']) && isset($dataInfo['game_id']))
                    $connection_all[$dataInfo['game_id']][$dataInfo['user_id']] = $connection->id; //保存连接

                $url = $baseUrl . "Game/getGameStatus";
                if(isset($dataInfo['user_id'])){
                	echo "user_id：{$dataInfo['user_id']}进入游戏：{$dataInfo['game_id']}房间中……连接id：{$connection->id}\n";
                }
                $httpData = https_post($data, $url);
                //给客户端推创建房间成功消息
                $connection->send($httpData);
                $httpData='';
                unset($httpData);
                break;
            case "SetBet"://下注 user_id game_id bet_id num
                $url = $baseUrl . "Game/setBet";
                if(isset($dataInfo['user_id']) && isset($dataInfo['game_id']) && isset($dataInfo['bet_id']) && isset($dataInfo['num'])){
                    echo "user_id：{$dataInfo['user_id']}在游戏id：{$dataInfo['game_id']} 下注id:{$dataInfo['bet_id']} 数量：{$dataInfo['num']}……";
                }
                $httpData = https_post($data, $url);
                //给客户端推下注成功消息
                sendToAll($httpData,$dataInfo['game_id']);
                $httpData='';
                unset($httpData);
                break;
            case "getWinResult":
                $url = $baseUrl . "Game/getWinResult";
                $httpData = https_post($data, $url);
                //给客户端推开奖消息
                $connection->send($httpData);
                $httpData='';
                unset($httpData);
                break;
            default:
                break;
        }
    }
};
//断开连接时执行
$ws_worker->onClose = function($connection) use($ws_worker, &$connection_all, &$timer_all) {
    if(isset($connection_all[2])){
        if(in_array($connection->id,$connection_all[2])){
            $baseUrl = "http://localhost/api/";
            $url = $baseUrl . "Game/sgjClose";
            $user_id=array_search($connection->id,$connection_all[2]);
            echo '用户'.$user_id.'断开，自动结算';
            https_post(json_encode(['user_id'=>$user_id]), $url);
        }
    }
    foreach($connection_all as $k=>$v){
        if(in_array($connection->id,$v)){
            $conn_key = array_search($connection->id, $v);
            unset($connection_all[$k][$conn_key]);
            break;
        }
    }
    echo "\n onClose触发操作结束：\n";
};

//运行worker  
$ws_worker->runAll();

function sendStatus(){
    global $ws_worker, $connection_all,$connection;
    //豪车漂移
    $time_status_config=[
        1=>15,
        2=>20,
        3=>5,
    ];
    $checkStatus=CheckStatus($time_status_config);
    $status=$checkStatus['status'];
    $second=$checkStatus['second'];
    switch ($status){
        case 1://下注时间
            if($second == 1){
                //开奖
                $baseUrl = "http://localhost/api/";
                //发送下注结束请求;
                $url = $baseUrl . "Game/getWinResult";
                $data=json_encode(["game_id"=>1]);
                $httpData = https_post($data, $url);
                $httpData_info=json_decode($httpData,true);
                if(isset($connection_all[1]) && is_array($connection_all[1])){
                    foreach ($connection_all[1] as $k=>$v) {
                        if (isset($ws_worker->connections[$v])) {
                            if(isset($httpData_info[$k])){
                                $msg=[
                                    "code"=>1,
                                    "operation"=>"ChangeStatus",
                                    "data"=>[
                                        'game_id'=>1,
                                        'status'=>2,
                                        'time'=>20,
                                        'win_bet'=>$httpData_info['win_bet'],
                                        'result'=>[
                                            'self_result'=>$httpData_info[$k]['self_result'],
                                            'banker_result'=>$httpData_info[$k]['banker_result'],
                                            'gold_else'=>$httpData_info[$k]['gold_else']
                                        ]
                                    ]
                                ];
                            }else{
                                $msg=[
                                    'code'=>1,
                                    "operation"=>"ChangeStatus",
                                    "data"=>[
                                        'game_id'=>1,
                                        'status'=>2,
                                        'time'=>20,
                                        'win_bet'=>$httpData_info['win_bet'],
                                        'result'=>[
                                            'self_result'=>0,
                                            'banker_result'=>0,
                                        ]
                                    ]
                                ];
                            }
                            $ws_worker->connections[$v]->send(json_encode($msg));
                        }
                    }
                }
                $httpData='';
                unset($httpData);
            }
            break;
        case 2://开奖时间
            if($second == 1){
                //发送开奖结束请求;
                sendToAll(json_encode([
                    'code'=>1,
                    "operation"=>"ChangeStatus",
                    "data"=>[
                        'game_id'=>1,
                        "status"=>3,
                        "time"=>5
                    ]
                ]),1);
            }
            break;
        case 3://休息时间
            if($second == 1){
                //发送休息结束请求;
                sendToAll(json_encode([
                    'code'=>1,
                    "operation"=>"ChangeStatus",
                    "data"=>[
                        'game_id'=>1,
                        "status"=>1,
                        "time"=>15
                    ]
                ]),1);
            }
            break;
        default:
            break;
    }
    //飞禽走兽
    //TODO::其他游戏定时器
}
function CheckStatus($time_status_config){
    $time_unit=0;//一回合总时间
    foreach($time_status_config as $v){
        $time_unit+=$v;
    }
    //当天过去的秒数
    $second=time()-strtotime(date('Y-m-d',time()).'00:00:00');
    //剩下多少时间
    $second_else=$second%$time_unit;
    $status=0;
    $second=$second_else;
    foreach($time_status_config as $k=>$v){
        if($second-$v>=0){
            $second-=$v;
        }else{
            $status=$k;
            $second=$v-$second;
            break;
        }
    }
    return ['status'=>$status,'second'=>$second];
}

function sendToAll($msg,$game_id) {//向某游戏所有成员发送同一条消息
    global $ws_worker, $connection_all, $timer_all;
    if(isset($connection_all[$game_id]) && is_array($connection_all[$game_id])){
        foreach ($connection_all[$game_id] as $k => $v) {
            if (isset($ws_worker->connections[$v])) {
                echo date('Y-m-d H:i:s')."\n当前发送给{$v} 的消息-{$msg}\n";
                $ws_worker->connections[$v]->send($msg);
            }
        }
    }

}

function https_post($data, $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20); // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8')
    );
    ob_start();
    curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch); //捕抓异常
    }
    $return_content = ob_get_contents();
    ob_end_clean();
    curl_close($ch);
    return $return_content;
}
